<template>


  <el-dialog :title="'用户' + (type == 'add'?'添加':'编辑' )" :visible="visible"  @close="visible = false">
    <el-form :model="form" ref="form" status-icon :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input :disabled="type == 'edit'" v-model="form.username" auto-complete="off"/>
      </el-form-item>
      <el-form-item label="所属部门" prop="depId">
        <dep-select v-model="form.depId"/>
      </el-form-item>
      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item label="权限" prop="roles">
        <role-select url="/api/v1/sdep/arls" @not-contain="notContain" v-model="form.roles"/>
      </el-form-item>
      <el-form-item label="已有权限" v-if="nCtn.length > 0">
        <span style="padding-right:10px;" :key="n.id" v-for="n in nCtn">{{n.name}}</span>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="form.idNo"/>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone"/>
      </el-form-item>
      <el-form-item label="e-mail">
        <el-input v-model="form.email"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.comment" type="textarea"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="onOk">确 定</el-button>
    </div>
  </el-dialog>

</template>

<script>
  import axios from '@/util/axios'

  import DepSelect from "@/components/DepSelect";
  import RoleSelect from "@/components/RoleSelect";
  import {isInArr,arrUnique} from "@/util/arr";

  const allRoles = [];
  const form = () => {
    return {
      roles:[]
    };
  }

  export default {

    components:{ DepSelect,RoleSelect },

    data(){
      return {
        visible:false,
        loading:false,
        type:'add',
        //不能修改的权限
        nCtn:[],
        form:form(),
        repassword:'',
        parentName:'',
        roles:undefined,
        timer:null,
        rules:{
          username:[{
            required: true, message: '请输入用户名', trigger: 'change'
          },{
            trigger:'change', min: 5, message: '最少5个字符'
          },{
            trigger:'change',pattern: /^[a-z\d_]+$/i, message: '必须是字母数字下划线'
          },{
            trigger: 'change',
            validator: (rule , value, callback) => {
              if(this.type == 'edit'){
                callback();
              }
              clearTimeout(this.timer);
              this.timer = setTimeout( () =>{
                axios.get('/api/v1/suser/exist',{params:{username:value}})
                .then(({data}) => {
                  if(data === true){
                    callback(new Error(`用户名 ${value} 已存在`));
                  }else {
                    callback();
                  }
                });
              },500);
            }
          }],
          depId:[{
            required: true, message: '请选择部门', trigger: 'change'
          }],
          name:[{
            required: true, message: '请输入真实姓名', trigger: 'blur'
          }],
          roles:[{
             required: true,  trigger: 'blur',
             validator:(rule,value,callback) => {
               if(this.nCtn.length == 0 && (!value || value.length == 0)){
                 callback(new Error('请选择权限'));
               }else{
                callback();
               }
             }
          }]
        }
      };

    },

    methods: {

      notContain(va){
        axios.post('/api/v1/suser/rolenames',axios.form({roles:va}))
        .then(({data})=>{
          data && (this.nCtn = data);
        })
      },

      onOk(){
        this.$refs.form.validate().then(() => {
          const exec = (this.type == 'add')? axios.put : axios.patch;
          this.loading = true;
          const fm = Object.assign([],this.form);
          fm.roles = Object.assign([],this.form.roles);
          if(this.nCtn.length > 0){
            for(const n of this.nCtn){
              if(!isInArr(n.id,fm.roles)){
                fm.roles.push(n.id);
              }
            }
          }
          fm.roles = arrUnique(fm.roles);
          exec('/api/v1/suser',axios.form(fm))
          .then(()=>{
            this.$message.success(((this.type == 'add') ? '添加':'修改') + '成功');
            this.visible = false;
            this.loading = false;
            this.$emit('success');
          })
          .catch( e => {
            setTimeout( e => this.loading = false,2000);
          });
        }).catch(e=>{});
      },

      add(){
        this.nCtn = [];
        this.visible = true;
        this.type = 'add';
        const fm = form();
        fm.depId = this.$session.depId;
        this.$refs.form && this.$refs.form.resetFields();
        setTimeout( e=> this.form = fm,50);
      },

      edit(id){
        this.nCtn = [];
        this.visible = true;
        this.type = 'edit';
        axios.get(`/api/v1/suser/get/${id}`)
        .then( ({data}) => {
          this.form = data;
        });
      }
    }
  }
</script>

